raise AssertionError("This mix-in requires there is a sibling class with a 'more' method. Additionally, CallbackProducerMixin must be *before* that class in the inheritance list (for method resolution reasons).")
def set_callback(self, callback = None):
self._callback = callback
set_callback = callsback(set_callback)
def more(self):
if not hasattr(self, '_siblingClass'):
result = ''
else:
result = self._siblingClass.more(self)
if result == '':
if getattr(self, '_callback', None) is not None:
self._callback.success()
if getattr(self, '_callback', None) is not None:
del self._callback
return result
class SimpleCallbackProducer(CallbackProducerMixin, asynchat.simple_producer):
def __init__(self, data):
asynchat.simple_producer.__init__(self, data)
CallbackProducerMixin.__init__(self)
def _fifo_remove(self, val):
try:
self.list.remove(val)
except Exception:
return False
return True
asynchat.fifo.remove = _fifo_remove
def producer_cb(data, callback = None):
prod = SimpleCallbackProducer(data)
prod.set_callback(callback = callback)
return prod
producer_cb = callsback(producer_cb)
def get_snurl(url):
return get_short_url(url, 'snurl')
def get_isgd(url):
return get_short_url(url, 'isgd')
def get_tinyurl(url):
return get_short_url(url, 'tinyurl')
class UrlShortener(object):
endpoint = None
def shorten(self, url):
try:
resp = urllib2.urlopen(UrlQuery(self.endpoint, d = self.get_args(url.encode('utf-8'))))
except urllib2.HTTPError:
e = None
resp = e
return self.process_response(resp)
def get_args(self, url):
raise NotImplementedError
def process_response(self, resp):
if resp.code != 200:
body = resp.read()
raise Exception(body)
ret = resp.read()
return ret
class isgd_shortener(UrlShortener):
endpoint = 'http://is.gd/api.php'
def get_args(self, url):
return dict(longurl = url)
class tinyurl_shortener(UrlShortener):
endpoint = 'http://tinyurl.com/api-create.php'
def get_args(self, url):
return dict(url = url)
class snipr_shortener(UrlShortener):
endpoint = 'http://snipr.com/site/snip'
def get_args(self, url):
return dict(r = 'simple', link = url.encode('url'))
def process_response(self, resp):
ret = UrlShortener.process_response(self, resp)
if not ret.startswith('http'):
raise Exception('bad url', ret)
return ret
_shorteners = {
'snipr': snipr_shortener,
'snurl': snipr_shortener,
'snipurl': snipr_shortener,
'isgd': isgd_shortener,
'tinyurl': tinyurl_shortener,
'tiny': tinyurl_shortener }
def get_short_url(url, provider = 'snipr'):
shortener = _shorteners.get(provider)
if shortener is None:
raise Exception('UrlShortener provider %r not found', provider)